<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="doctorName">
              <el-input v-model="filters.doctorName" clearable placeholder="医生名称"></el-input>
            </el-form-item>
            <el-form-item prop="state">
              <el-select v-model="filters.state" :clearable="true" placeholder="医生状态">
                <el-option v-for="item in agenciesStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button type="success" plain icon="fa fa-plus" v-has="permissionBatchNuclePrice" @click="handleClickBatchNuclePrice()" size="mini"> 批量绑定采样价格</el-button>
            <el-button type="success" plain icon="el-icon-suitcase" v-has="permissionBatchSetBusinessMan" @click="handleClickBatchSetBusinessMan()" size="mini"
              >批量设置业务员</el-button
            >
          </div>
          <!--<span class="line">|</span>-->
          <!--<el-button type="primary" icon="fa fa-mail-forward">导出</el-button>-->
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table :data="doctorList" @selection-change="changeSelect" :fit="true" highlight-current-row>
        <!--<el-table-column prop="doctorId" label="医生ID" width="80"></el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column label="医生头像" width="100">
          <template slot-scope="scope">
            <img :src="scope.row.doctorImageUrl" class="photo">
          </template>
        </el-table-column> -->
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="doctorName" label="医生姓名" width="200"></el-table-column>
        <el-table-column prop="doctorSex" label="性别" width="80" :formatter="formatSex"></el-table-column>
        <el-table-column prop="doctorTitle" label="职称" width="80"></el-table-column>
        <el-table-column prop="hospitalName" label="所属医院" width="300"></el-table-column>
        <el-table-column prop="institutionName" label="所属医检" width="300"></el-table-column>
        <el-table-column prop="officeName" label="所属科室"></el-table-column>
        <el-table-column prop="doctorAddress" label="地址" width="200"></el-table-column>
        <el-table-column label="医生状态" width="100" align="center">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createDate" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="150" align="left">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state == 0 ? '启用' : '禁用' }}</el-dropdown-item>
                <el-dropdown-item v-has="permissionDelete" v-if="scope.row.state == 0" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <!--设置业务员组件 -->
    <BatchSetBusinessMan ref="batchSetBusinessMan" :relation-type="4"></BatchSetBusinessMan>

    <el-dialog title="批量绑定采样价格模板" :visible.sync="hideDialogShow" :center="true" width="600px">
      <el-form :model="dataForm" ref="dataForm" :rules="roleRules" label-width="150px">
        <el-form-item label="采样价格模板" prop="modelId">
          <el-select v-model="dataForm.modelId" filterable clearable reserve-keyword placeholder="请选择采样价格模板">
            <el-option v-for="item in pickNuclePriceModelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item align="center">
          <el-button type="primary" plain @click.native="clickCommit">确 定</el-button>
          <el-button @click.native="clickCancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import { FORMAT_DATE_YYYY_MM_DD } from '@/constants/constants';
import DoctorApi from '@/api/institution/doctor';
import NuclePriceApi from '@/api/sample/nuclePrice';
import BatchSetBusinessMan from '@/components/BatchSetBusinessMan';

export default {
  name: 'DoctorManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      doctorList: [],
      filters: {
        doctorName: '',
        doctorTitle: '',
        state: null,
      },
      selectIds: [],
      pickNuclePriceModelList: [],
      pageLoading: false,
      hideDialogShow: false,
      dataForm: {
        modelId: '',
        idList: [],
        type: 3,
      },
      roleRules: {
        mainFlag: [{ required: true, message: '请选择采样价格模板', trigger: 'change' }],
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      reviewStatue: [
        { label: '审核驳回', value: -1 },
        { label: '待审核', value: 0 },
        { label: '审核通过', value: 1 },
      ],
      agenciesStatue: [
        { label: '禁用', value: '0' },
        { label: '启用', value: '1' },
      ],

      permissionAdd: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_DELETE',
      permissionBatchNuclePrice: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_BATCH_NUCLE_PRICE',
      permissionBatchSetBusinessMan: 'SYSTEM_MANAGER_INSTITU_DOCTOR_LIST_BATCH_SET_BUSINESS_MAN',
      excelData: {},
      allList: [],
    };
  },
  computed: {},
  components: {
    BatchSetBusinessMan,
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.init();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.listDoctor();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    clickCommit() {
      this.$confirm(message.MSG_CONFIRM_BATCH_SAMPLE_PRICE, message.TITLE_PROMPT, {}).then(() => {
        this.dataForm.idList = this.selectIds;
        NuclePriceApi.bindModel(this.dataForm).then((res) => {
          this.hideDialogShow = false;
          this.$Utils.notifySuccess();
          this.listDoctor();
        });
      });
    },
    clickCancel() {
      this.hideDialogShow = false;
    },
    handleClickBatchNuclePrice() {
      this.hideDialogShow = true;
      this.dataForm.modelId = '';
      if (!this.pickNuclePriceModelList || this.pickNuclePriceModelList.length == 0) {
        this.getNuclePriceModelList();
      }
    },
    handleClickBatchSetBusinessMan() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        _this.$refs.batchSetBusinessMan.handleCreate(this.selectIds);
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请至少选择一条记录！',
        });
      }
    },
    getNuclePriceModelList() {
      let _this = this;
      NuclePriceApi.listModelName({}).then((res) => {
        setTimeout(() => {
          _this.pickNuclePriceModelList = res.data.map((item) => {
            return {
              value: item.id,
              label: item.name,
            };
          });
        }, 200);
      });
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].doctorId);
      }
    },
    formatSex(row, column, cellValue) {
      if (cellValue == 1) {
        return '男';
      } else if (cellValue == 2) {
        return '女';
      }
    },
    formatApproveState(row, column, cellValue) {
      if (cellValue == -1) {
        return '审核驳回';
      } else if (cellValue == 0) {
        return '待审核';
      } else if (cellValue == 1) {
        return '审核通过';
      }
    },
    formatState(cellValue) {
      if (cellValue == -1) {
        return '删除';
      } else if (cellValue == 0) {
        return '禁用';
      } else if (cellValue == 1) {
        return '启用';
      } else if (cellValue == 2) {
        return '审核';
      }
    },
    formatStates(cellValue) {
      if (cellValue == -1) {
        return 'danger';
      } else if (cellValue == 0) {
        return 'info';
      } else if (cellValue == 1) {
        return 'success';
      } else if (cellValue == 2) {
        return 'warning';
      }
    },
    formatDate(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, FORMAT_DATE_YYYY_MM_DD);
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listDoctor();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listDoctor();
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/institu/doctorEdit',
        query: { id: row.doctorId },
      });
    },
    /* handleClickQualificationsEditor(row){
      this.$router.push({path: "/user/DoctorQualificationEdit", query: {id: row.doctorId}})
    },
    handleClickHonourEditor(row){
      this.$router.push({path: "/user/DoctorHonourEdit", query: {id: row.doctorId}})
    },
    handleClickAdManager(row){
      this.$router.push({path: "/user/DoctorAdManager", query: {id: row.doctorId}})
    },*/
    handleIsDisable(row) {
      let _this = this;
      let currentState = '';
      if (row.state == 0) {
        currentState = 1;
      } else {
        currentState = 0;
      }
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        DoctorApi.deleteDoctor({
          doctorId: row.doctorId,
          state: currentState,
        }).then((res) => {
          _this.listDoctor();
        });
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        DoctorApi.deleteDoctor({
          doctorId: val.doctorId,
          state: -1,
        }).then((res) => {
          _this.listDoctor();
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/institu/doctorAdd');
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/institu/doctorDetail',
        query: { id: row.doctorId },
      });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listDoctor();
    },
    listDoctor() {
      let _this = this;
      // page + condition
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      let doctorName = _this.filters.doctorName;
      //let approveState = _this.filters.approveState
      let state = _this.filters.state;

      if (doctorName !== undefined && doctorName !== null && doctorName !== '') {
        cond.doctorName = doctorName;
      }
      /*if (approveState !== undefined && approveState !== null && approveState !== '') {
        cond.approveState = approveState
      }*/
      if (state !== undefined && state !== null && state !== '') {
        cond.state = state;
      }
      DoctorApi.getDoctorList(cond).then((res) => {
        _this.doctorList = res.data.list;
        _this.page.pageTotal = res.data.total;
      });
    },
    sureDoctorClick() {
      _this.$refs.doctorForm.validate((valid) => {
        if (valid) {
          _this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
            // //debugger
            if (_this.doctorForm.doctorId) {
              _this.alterDoctor();
            } else {
              _this.addDoctor();
            }
          });
        }
      });
    },
    alterDoctor() {
      let _this = this;
      DoctorApi.editDoctor(_this.doctorForm).then((data) => {
        this.dialogVisible = false;
        _this.listDoctor();
        _this.$Utils.notifySuccess();
      });
    },
    addDoctor() {
      let _this = this;
      DoctorApi.addDoctor(this.doctorForm).then((data) => {
        this.dialogVisible = false;
        _this.listDoctor();
        _this.$Utils.notifySuccess();
      });
    },
    handleClickExport() {
      if (!this.allList) {
        this.$notify.error({
          title: message.TITLE_ERROR,
          message: '数据加载错误',
        });
        return;
      }
      this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.excelData = this.allList;
          this.export2Excel();
        })
        .catch(() => {});
    },
    export2Excel() {
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel'); //这里必须使用绝对路径
        const tHeader = ['医生ID', '医生名称', '医生头像地址', '所属机构', '创建人账号', '创建人ID', '创建时间', '医生描述', '医生职称']; // 导出的表头名
        const filterVal = ['doctorId', 'doctorName', 'doctorImageUrl', 'hospitalName', 'createUserName', 'createUserId', 'createDate', 'doctorIntroduce', 'doctorTitle']; // 导出的表头字段名
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        let time1,
          time2 = '';

        export_json_to_excel(tHeader, data, `[${time1}-${time2}]医生管理列表`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
